package com.btkjgc.controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.btkjgc.models.AdminUser;
import com.btkjgc.models.CarAccount;
import com.btkjgc.models.CarT;
import com.btkjgc.models.CartypePostage;
import com.btkjgc.models.email.EmailResult;
import com.btkjgc.models.extend.AccountUserModel;
import com.btkjgc.models.extend.AdminUserModel;
import com.btkjgc.service.impl.AdminUserManageService_Impl;
import com.btkjgc.service.impl.LoginService_Impl;
import com.btkjgc.service.impl.LeftBarManager_Impl;
import com.btkjgc.service.impl.RoleFunctionService_Impl;
import com.btkjgc.service.intf.AdminUserManageService_Intf;
import com.btkjgc.utils.Constant;
import com.btkjgc.utils.FtlOperationUtil;
import com.btkjgc.utils.HibernateUtil;
import com.btkjgc.utils.JsonUtil;
import com.btkjgc.utils.SendEmail;

/**
 * Created by Administrator on 14-3-6.
 */
@Controller
public class LoginController
{

	Logger logger = Logger.getLogger(LoginController.class);

 

	LoginService_Impl loginService = new LoginService_Impl();
	AdminUserManageService_Intf adminUserManageService = new AdminUserManageService_Impl();

	RoleFunctionService_Impl roleFunctionService = new RoleFunctionService_Impl();

	// 忘记密码，通过邮箱找回密码
	@RequestMapping(value = { "/login/forgetpw" })
	public ModelAndView forgetPW(HttpServletRequest request,
			HttpServletResponse response) throws IOException
	{
		
		String loginname = request.getParameter("loginname");
		// 若loginname = null表明还未设置要找回密码的账号
		if (loginname == null) { return new ModelAndView("login"); }
		// 如果已经设置了要找回密码的账号
		AdminUser adminUser = loginService.getAdminByName(loginname);
		EmailResult result = new EmailResult();
		if (adminUser == null)
		{// 账号不存在
			result.setResult(Constant.SEND_ADMIN_NOT_EXIST);
		}
		else
		{
			if (FtlOperationUtil.isNull(adminUser.getEmail())
					|| !SendEmail.isEmailFormat(adminUser.getEmail()))
			{// 邮箱不合法
				result.setResult(Constant.SEND_EMAIL_NOT_LEGAL);
			}
			else
			{
				try
				{
					result.setResult(Constant.SEND_SUCCESS);
					result.setContent(adminUser.getEmail());
					adminUser.setPw_retrieve_time(""
							+ System.currentTimeMillis());
					loginService.updateAdmin(adminUser);
					SendEmail.pwRetrieveByEmail(adminUser.getEmail(), loginname,
							adminUser.getPw_retrieve_time());// 发送邮件
				}
				catch (Exception e)
				{
					result.setResult(Constant.SEND_ERROR);
					e.printStackTrace();
				}
			}
		}

		// 设置输出的编码格式
		response.setCharacterEncoding("utf-8");
		PrintWriter printer = response.getWriter();
		printer.print(JSON.toJSONString(result));
		printer.flush();
		printer.close();
		return null;
	}

	// 重设密码（邮箱链接处理）
	@RequestMapping(value = { "/login/pwretrieve" })
	public ModelAndView pwRetrieve(HttpServletRequest request,
			HttpServletResponse response)
	{
		// 需要加上id加密设置
		String loginname = request.getParameter("user");
		if (!FtlOperationUtil.isNull(loginname))
		{
			String id = request.getParameter("id");
			AdminUser admin = loginService.getAdminByName(loginname);
			if (!FtlOperationUtil.isNull(admin.getPw_retrieve_time()))
			{
				long duration = System.currentTimeMillis()
						- Long.parseLong(admin.getPw_retrieve_time());
				duration = duration / 1000 / 60;// 分钟
				String code = admin.getPw_retrieve_time();
				if (duration <= 30 && id.equals(code))
				{// 验证码
					ModelAndView mv = new ModelAndView("pwretrieve");
					mv.addObject("loginname", loginname);
					return mv;
				}
			}
			ModelAndView mv = new ModelAndView("pw_retrieve_result");
			mv.addObject("url", Constant.ABSOLUTE_URL + "login");
			return mv;
		}
		return new ModelAndView("redirect:/login");
	}

 

	// 获取登陆页面，跳转到登陆页面login.ftl
	@RequestMapping(value = { "login" }, method = { RequestMethod.GET })
	public ModelAndView getLoginPage(HttpServletRequest request)
	{
		AdminUser usr = (AdminUser) request.getSession().getAttribute("user");
		String url = request.getRequestURL().toString();
		Constant.ABSOLUTE_URL = url.substring(0, url.length() - 5);
		if (usr != null)
		{
			int roleId = roleFunctionService.getRoleId(usr.getId());
			ModelAndView mv = new ModelAndView("redirect:/index");
		 
			return mv;
		}
		else
		{
			ModelAndView mv = new ModelAndView("login");

			Boolean alreadyLogin = (Boolean) request.getSession().getAttribute(
					"alreadyLogin");
			if (alreadyLogin != null && alreadyLogin)
			{
				mv.addObject("alreadyLogin", true);
			}
			return mv;
		}
	}

	// 实现用户登陆操作，跳转到后台管理程序首页index.ftl
	@RequestMapping(value = "do_login", method = { RequestMethod.POST })
	public ModelAndView doLogin(
			HttpServletRequest request,
			@RequestParam(value = "loginname", required = true) String loginname,
			@RequestParam(value = "passwords", required = true) String password)
	{
		// 从数据库取出这一行
		AdminUser adminUser = loginService.getAdminByName(loginname);
		if (adminUser != null
				&& adminUser.getPassword().equals(DigestUtils.md5Hex(password)))
		{
			// 登录成功，更新上次登录的ip地址
			String lastIp = request.getRemoteAddr();
			loginService.updateLastLoginTp(adminUser.getId(), lastIp);
			// adminUser.setLastip(lastIp);

			int roleId = roleFunctionService.getRoleId(adminUser.getId());
			// 登录成功，取出登陆者信息
			adminUser.setRoleId(roleId);
			AdminUserModel adminUserModel =new AdminUserModel();
			try {
				PropertyUtils.copyProperties(adminUserModel, adminUser);
			} catch (IllegalAccessException | InvocationTargetException
					| NoSuchMethodException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			adminUserModel.setRoleLevel(BigInteger.valueOf(HibernateUtil.executeSQLQueryInt("select  level from role_t where id="+adminUser.getRoleId())));
			request.getSession().setAttribute("user", adminUserModel);
 
			// 修改上次登录时间和登录次数
			// 先获取时间
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// 设置日期格式
			String loginTime = df.format(new Date());// new Date()为获取当前系统时间
			// 获取loginname的id(主键)
			String userID = adminUser.getId() + "";
			String hqlUpdateLastLoginTime = "update AdminUser set lastlogin =?, logintimes =logintimes + 1 where id=?";
			String[] parameter = { loginTime, userID };
			HibernateUtil.executeUpdate(hqlUpdateLastLoginTime, parameter);
			
			//将两周后到期的个人车辆自动解绑
			String sql = " select * from car_account_t where del=2";
			List<CarAccount> carAccountList = HibernateUtil.executeSQLQueryList(sql, CarAccount.class);
			
			if(carAccountList.size()!=0||!carAccountList.isEmpty()){
				for(int i=0;i<carAccountList.size();i++){
					Date begin = new Date();
					Date end = carAccountList.get(i).getUnbinddate();
					long between=(begin.getTime()-end.getTime())/1000;
					if(between>=1209600){//大于等于14天，自动解绑
						if(carAccountList.get(i).getSelf()==1){//自有车
							String hql = " update from CarAccount set carid=null,del=1,cartypeid=null,carbrand=null where id="+carAccountList.get(i).getId();
							HibernateUtil.executeUpdate(hql);
							//更新car_account_log_t表
							String loghql = " update from CarAccountLog set del=1,unbinddate='"+df.format(new Date())+"' where accountid="+carAccountList.get(i).getAccountid()+" and del=0";
							
							HibernateUtil.executeUpdate(loghql);
							//删除套餐
							String deletesql = " select * from cartype_postage_t where accountid="+carAccountList.get(i).getAccountid();
							CartypePostage cartypePostage = (CartypePostage)HibernateUtil.executeSQLQueryObject(deletesql, CartypePostage.class);
							if(cartypePostage!=null){
								HibernateUtil.delete(cartypePostage);
							}
							
						}else{//非自有车
							String hql1 = " update from CarAccount set carid=null,del=1,cartypeid=null,carbrand=null where carid="+carAccountList.get(i).getCarid();
							HibernateUtil.executeUpdate(hql1);
							//更新car_account_log_t表
							String loghql = " update from CarAccountLog set del=1,unbinddate='"+df.format(new Date())+"' where accountid="+carAccountList.get(i).getAccountid()+" and del=0";
							
							HibernateUtil.executeUpdate(loghql);
							//同时删除该账户所属公司及套餐
							String hql2 = " update from AccountUser set company=null where id="+carAccountList.get(i).getAccountid();
							HibernateUtil.executeUpdate(hql2);
							
							String deletesql = " select * from cartype_postage_t where accountid="+carAccountList.get(i).getAccountid();
							CartypePostage cartypePostage = (CartypePostage)HibernateUtil.executeSQLQueryObject(deletesql, CartypePostage.class);
							HibernateUtil.delete(cartypePostage);
						}
					}
				}
			}

			Map<String, Map<String, Boolean>> roleFunction = roleFunctionService
					.getRoleFunction(roleId);
			if (roleFunction != null && roleFunction.size() > 0)
				request.getSession()
						.setAttribute("role_function", roleFunction);
				request.getSession().setAttribute("role_id", roleId);
				request.getSession().setAttribute("role_level",
						roleFunctionService.getRoleLevel(roleId));
	
				request.getSession().setAttribute("left_menu",
						(new LeftBarManager_Impl()).getLeftMenuByRoleId(roleId));
				ModelAndView mv = null;
	            mv = new ModelAndView("redirect:/index");
		 
			return mv;
		}
		else
		{
			ModelAndView mv = new ModelAndView("login");
			mv.addObject("wrongpw", "wrongpw");
			mv.addObject("loginname", loginname);
			return mv;
		}
	}

	// 实现用户注销操作，跳转到登陆页面login.ftl
	@RequestMapping(value = "do_logout", method = { RequestMethod.GET })
	public ModelAndView doLogout(HttpServletRequest request)
	{
		request.getSession().invalidate();
		ModelAndView mv = new ModelAndView("login");
		return mv;
	}
 

}
